package com.wac.data.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wac.data.entity.Dynamic;
import com.wac.data.service.DynamicService;
import com.wac.data.service.UserService;
import com.wac.data.utils.DataListUtil;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author beta
 * @since 2023-03-16
 */
@RestController
@RequestMapping("/dynamic")
public class DynamicController {

	private static ObjectMapper objectMapper = new ObjectMapper();

	@Resource
	private DynamicService dynamicService;
	@Resource
	private UserService userService;

	//发布动态
	@RequestMapping("/issue_file")
	public String articleIssueFile(@RequestPart("dynamic") Dynamic dynamic, @RequestPart("file") List<MultipartFile> file) {
		if (dynamicService.addDynamic(dynamic, file)) {
			return "success";
		}
		return "failed";
	}

	@RequestMapping("/issue_text")
	public String articleIssueText(@RequestPart("dynamic") Dynamic dynamic) {
		if (dynamicService.addDynamic(dynamic, null)) {
			return "success";
		}
		return "failed";
	}

	//获取动态
	@RequestMapping("/list")
	public String dynamicGet(int page) throws JsonProcessingException {
		return objectMapper.writeValueAsString(dynamicService.getDynamic(page));
	}

	//获取指定用户动态
	@RequestMapping("/user")
	public String dynamicUser(int page, String id) throws JsonProcessingException {
		return objectMapper.writeValueAsString(dynamicService.getDynamicByUserId(page, id));
	}

	//id拿动态
	@RequestMapping("/one")
	public String getDynamicById(String id, HttpServletRequest request) throws JsonProcessingException {
		String userId = userService.isUserLogin(new DataListUtil().getCookies(request));
		return objectMapper.writeValueAsString(dynamicService.getDynamicById(id, userId));
	}

	@RequestMapping("/delete")
	public String dynamicDelete(String id) {
		if (dynamicService.delete(id)) {
			return "1";
		}
		return "0";
	}


}

